<template>
  <div class="register-container">
    <el-form :model="registerForm" :rules="registerRules" ref="registerForm" label-width="80px">
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="registerForm.userName" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="userPwd">
        <el-input v-model="registerForm.userPwd" type="password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="registerForm.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitRegister('registerForm')">注册</el-button>
        <el-button @click="resetForm('registerForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'Register',
  data() {
    return {
      registerForm: {
        userName: '',
        userPwd: '',
        email: ''
      },
      registerRules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { pattern: /^[A-Za-z]+$/, message: '用户名必须是英文', trigger: 'blur' }
        ],
        userPwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8}$/,
            message: '密码必须是8位并且至少包含数字和英文',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitRegister(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$http.post('/userInfo/addAdmin', JSON.stringify(this.registerForm), {
            headers: {
              'Content-Type': 'application/json'
            }
          })
            .then(response => {
              if (response.data.code === 200) {
                this.$message.success('注册成功！');
                this.resetForm('registerForm');
              } else {
                this.$message.error(response.data.msg || '注册失败');
              }
            })
            .catch(error => {
              this.$message.error('注册失败：' + error.message);
            });
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style scoped>
.register-container {
  width: 400px;
  margin: 20px auto;
}
</style>
